package cn.itsource.upload.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.itsource.upload.service.IMinioService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class MinioServiceImpl implements IMinioService {
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucketname}")
    private String bucketName;
    @Override
    public String upload(MultipartFile file) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {


        //获取文件名
        String filename = file.getOriginalFilename();
        //获取文件后缀
        String suffix = FileNameUtil.getSuffix(filename);
        //随机生成文件名
        String fileName = System.currentTimeMillis() + "." + suffix;

        PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucketName)
                .object(fileName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType()).build();
        //文件名称相同覆盖
        minioClient.putObject(objectArgs);
        return fileName;
    }
}
